
#include "grabcut.h"
#include <iostream>
#include <fstream>

using namespace std;

// Segment image and return matrix where each of pixel is labed foreground or background
// Double percent_rectangle is larger than 0 and less than 1
void Grabcut::segment(Mat image, double percent_rectangle) {

	// Choose length rectangle at center point of image
	int rec_cols = image.cols * percent_rectangle;
	int rec_rows = image.rows * percent_rectangle;
	int length_diagonal_image = sqrt((double) image.cols * image.cols + image.rows * image.rows);
	int length_diagonal_rect = sqrt((double) rec_cols * rec_cols + rec_rows * rec_rows);

	int length_triangle = length_diagonal_image - length_diagonal_rect;
	int x_rect = rec_cols * length_triangle / length_diagonal_image;
	int y_rect = rec_rows * length_triangle / length_diagonal_image;
    // define bounding rectangle 
	cv::Rect rectangle(x_rect,y_rect,rec_cols,rec_rows);

    cv::Mat bgModel,fgModel; // the models (internally used)

    // GrabCut segmentation
    cv::grabCut(image,    // input image
                    mask,   // segmentation result
                            rectangle,// rectangle containing foreground 
                            bgModel,fgModel, // models
                            1,        // number of iterations
							cv::GC_INIT_WITH_RECT); // use rectangle
    // Get the pixels marked as likely foreground
    cv::compare(mask, cv::GC_PR_FGD, mask, cv::CMP_EQ);
}

Mat Grabcut::loadMask() {
	return mask;
}